﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.IRepository;
using CoreCms.Net.IRepository.UnitOfWork;
using CoreCms.Net.IServices;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.ViewModels.Basics;
using CoreCms.Net.Model.ViewModels.DTO;
using CoreCms.Net.Model.ViewModels.UI;
using SqlSugar;

namespace CoreCms.Net.Services
{
    /// <summary>
    ///    经纪人申请退出表 接口实现
    /// </summary>
    public class XrcBrokerExitServices : BaseServices<XrcBrokerExit>, IXrcBrokerExitServices
    {
        private readonly IXrcBrokerExitRepository _dal;
        private readonly IUnitOfWork _unitOfWork;

        public XrcBrokerExitServices(IUnitOfWork unitOfWork, IXrcBrokerExitRepository dal)
        {
            _dal = dal;
            BaseDal = dal;
            _unitOfWork = unitOfWork;
        }
        /// <summary>
        ///     获取我的团队列表
        /// </summary>
        /// <param name="predicate">判断集合</param>
        /// <param name="orderByType">排序方式</param>
        /// <param name="pageIndex">当前页面索引</param>
        /// <param name="pageSize">分布大小</param>
        /// <param name="orderByExpression"></param>
        /// <returns></returns>
        public   List<BrokerListDto> QueryListAsync( int userId,string where, OrderByType orderByType, int pageIndex = 1,
            int pageSize = 20)
            {
            if (where == null) {
                where = "";
                    }
            var list =   _unitOfWork.GetDbClient().Queryable<XrcApplyBroker, XrcOrder>((a, o) => new JoinQueryInfos(
               JoinType.Left, a.Userid == o.BrokerId
           ))
                
            .Where((a,o)=> a.ParentId ==userId && a.Name.Contains(where))
            .GroupBy((a, o) => a.Id)
            .OrderBy((a, o) => SqlFunc.AggregateCount(o.Id), orderByType)
            .Select((a, o) => new BrokerListDto()
            {
                Id = a.Id,
                BrokerName = a.Name,
                avatar = SqlFunc.Subqueryable<CoreCmsUserWeChatInfo>().Where(o => o.id ==a.Userid).Select(s =>  s.avatar),
                Limit = SqlFunc.Subqueryable<XrcOrder>().Where(o=>o.IsLoin==1 && o.BrokerId ==a.Userid).Select(s=>SqlFunc.AggregateSum(o.RealityQuota)),
                OrderCount = SqlFunc.Subqueryable<XrcOrder>().Where(o => o.State == 1 && o.BrokerId == a.Userid).Select(s => SqlFunc.AggregateCount(o.Id)),
                parentId = Convert.ToInt32(a.ParentId),
                State =a.state,
                Scale = a.scale
            }).ToList();

            return list;
        }
       
    }
}